package com.ogawa.joypal

import android.content.ComponentCallbacks2
import android.os.Process
import android.text.TextUtils
import com.bumptech.glide.Glide
import com.ogawa.base.BuildConfig
import com.ogawa.base.base.BaseApp
import com.tencent.bugly.crashreport.CrashReport
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException

class MainApplication : BaseApp() {

    override fun onCreate() {
        super.onCreate()
        initBugly()
        initARouter()
        initUM()
    }

    override fun onTrimMemory(level: Int) {
        super.onTrimMemory(level)
        if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
            Glide.get(this).clearMemory()
        }
        Glide.get(this).trimMemory(level)
    }

    override fun onLowMemory() {
        super.onLowMemory()
        Glide.get(this).clearMemory()
    }

    private fun initBugly() {
        // 获取当前包名
        val packageName = applicationContext.packageName
        // 获取当前进程名
        val processName: String? = getProcessName(Process.myPid())
        // 设置是否为上报进程
        val strategy = CrashReport.UserStrategy(applicationContext)
        strategy.isUploadProcess = processName == null || processName == packageName
        //初始化Bugly
        CrashReport.initCrashReport(this, "74a8e42daa", BuildConfig.DEBUG)
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private fun getProcessName(pid: Int): String? {
        var reader: BufferedReader? = null
        try {
            reader = BufferedReader(FileReader("/proc/$pid/cmdline"))
            var processName = reader.readLine()
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim { it <= ' ' }
            }
            return processName
        } catch (throwable: Throwable) {
            throwable.printStackTrace()
        } finally {
            try {
                reader?.close()
            } catch (exception: IOException) {
                exception.printStackTrace()
            }
        }
        return null
    }

    private fun initUM() {
        UMConfigure.init(this, "605c4f126ee47d382b964227", "Umeng", UMConfigure.DEVICE_TYPE_PHONE, "")
//        UMConfigure.preInit(
//            this,
//            "605c4f126ee47d382b964227",
//            "Umeng"
//        )
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO)
    }
}